<template>
    <el-drawer
        size="30%"
        v-model="drawer"
        :title="'添加房型'"
        direction="rtl"
        :before-close="closeDrawer">
            <el-form
            size="small"
            ref="formRef"
            style="max-width: 600px"
            :model="formData"
            status-icon
            :rules="rules"
            label-width="60px"
        >

   
    <el-form-item label="房间类型" prop="roomType">
        <el-input v-model="formData.roomType" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="房间价格" prop="price">
        <el-input v-model="formData.price" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="容纳人数" prop="peopleNum">
        <el-input v-model="formData.peopleNum" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="房间数量" prop="roleName">
        <el-input v-model="formData.roomNum" style="width: 300px;" />
    </el-form-item>

    <el-form-item label="有无早餐" prop="haveMeal">
          <el-radio-group v-model="formData.haveMeal" style="width: 300px;">
          <el-radio :label="true">有早餐</el-radio>
          <el-radio :label="false">无早餐</el-radio>
        </el-radio-group>
    </el-form-item>

   <el-form-item label="房间图片" prop="roomImage">
      <el-upload
        class="upload-demo"
        action=""
        :on-change="handleChange"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :multiple="true"
        :limit="5"
        list-type="picture-card"
      >
        <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500KB</div>
      </el-upload>
    </el-form-item>
   

    <el-form-item label="选择房型设施" prop="roomtypeFacilities">
      <el-checkbox-group v-model="formData.roots">
        <el-checkbox
          v-for="facility in facilityList"
          :key="facility.id"
          :label="facility.facilityInfo"
          :value="facility.id"
        >
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">{{'添加' }}</el-button>
        <el-button @click="resetForm(formRef)">取消</el-button>
    </el-form-item>

    </el-form>
    </el-drawer>
    <el-drawer
        size="30%"
        v-model="drawer2"
        :title="'修改房型'"
        direction="rtl"
        :before-close="closeDrawer2">
            <el-form
            size="small"
            ref="formRef2"
            style="max-width: 600px"
            :model="formData2"
            status-icon
            :rules="rules2"
            label-width="60px"
        >

    <el-form-item v-if="false" label="id" prop="id" >
        <el-input  v-model="formData2.id"  style="width: 300px;"  type="password"/>
    </el-form-item>
    <el-form-item label="房间类型" prop="roomType">
        <el-input v-model="formData2.roomType" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="房间价格" prop="price">
        <el-input v-model="formData2.price" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="容纳人数" prop="peopleNum">
        <el-input v-model="formData2.peopleNum" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="房间数量" prop="roleName">
        <el-input v-model="formData2.roomNum" style="width: 300px;" />
    </el-form-item>

    <el-form-item label="有无早餐" prop="haveMeal">
          <el-radio-group v-model="formData2.haveMeal" style="width: 300px;">
          <el-radio :label="true">有早餐</el-radio>
          <el-radio :label="false">无早餐</el-radio>
        </el-radio-group>
    </el-form-item>

   <el-form-item label="房间图片" prop="roomImage">
      <el-upload
        class="upload-demo"
        action=""
        :on-change="handleChange2"
        :on-remove="handleRemove2"
        :file-list="fileList2"
        :auto-upload="false"
        :multiple="true"
        :limit="5"
        list-type="picture-card"
      >
        <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500KB</div>
      </el-upload>
    </el-form-item>
    
    <el-form-item label="选择房型设施" prop="roomtypeFacilities">
      <el-checkbox-group v-model="formData2.roots">
        <el-checkbox
          v-for="facility in facilityList"
          :key="facility.id"
          :label="facility.facilityInfo"
          :value="facility.id"
        >
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="submitForm2(formRef2)">{{'修改' }}</el-button>
        <el-button @click="resetForm2(formRef2)">取消</el-button>
    </el-form-item>

    </el-form>
    </el-drawer>
</template>

<script setup lang="ts">
import type {FormInstance, FormRules, UploadProps} from 'element-plus';
import { ElNotification} from "element-plus";
import {onMounted, reactive, ref} from "vue";
import {$add, $findFacility,$update} from "../../api/roomType.ts";

const emit = defineEmits(['sync-list'])
const fileList = ref([]);
const fileList2 = ref([])


const handleRemove: UploadProps['onRemove'] = (file) => {
  const index = fileList.value.indexOf(file);
  if (index > -1) {
    fileList.value.splice(index, 1); // 从文件列表中移除文件
  }
};

const handleRemove2: UploadProps['onRemove'] = (file) => {
  const index = fileList2.value.indexOf(file);
  if (index > -1) {
    fileList2.value.splice(index, 1); // 从文件列表中移除文件
  }
};
//抽屉变量
const drawer = ref(false)
const drawer2 = ref(false)
//关闭抽屉
const closeDrawer = () =>{
    drawer.value =false
    //重置表单
    formRef.value?.resetFields()
    //清空表单
    formData.value = {
      roomType:'',
      peopleNum:'',
      price:'',
      haveMeal:'',
      roomNum:'',
    }
}
const closeDrawer2 = () =>{
    drawer2.value =false
    //重置表单
    formRef2.value?.resetFields()
    //清空表单
    formData2.value = {
      roomType:'',
      peopleNum:'',
      price:'',
      haveMeal:'',
      roomNum:'',
      roots:[]
    }
}

const formRef = ref<FormInstance>()
const formRef2 = ref<FormInstance>()
//表单数据
const formData = ref({
  roomType:'',
  peopleNum:'',
  price:'',
  haveMeal:'',
  roomNum:'',
  roots:[]
})

const formData2 = ref({
  id:'',
  roomType:'',
  peopleNum:'',
  price:'',
  haveMeal:'',
  roomNum:'',
  roots:[],
})

// 验证函数
const validateRoomType = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入房间类型'));
  } else {
    callback();
  }
};

const validatePeopleNum = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入人数'));
  } else if (isNaN(Number(value))) {
    callback(new Error('人数必须是数字'));
  } else {
    callback();
  }
};

const validatePrice = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入价格'));
  } else if (isNaN(Number(value))) {
    callback(new Error('价格必须是数字'));
  } else {
    callback();
  }
};

const validateHaveMeal = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请选择是否包含餐食'));
  } else {
    callback();
  }
};

const validateRoomNum = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入房间数量'));
  } else if (isNaN(Number(value))) {
    callback(new Error('房间数量必须是数字'));
  } else {
    callback();
  }
};

const validateRoots = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback(new Error('请选择至少一个房型设施'));
  } else {
    callback();
  }
};



// 验证对象
const rules2 = reactive<FormRules<typeof formData2>>({
  roomType: [{ validator: validateRoomType, trigger: 'blur' }],
  peopleNum: [{ validator: validatePeopleNum, trigger: 'blur' }],
  price: [{ validator: validatePrice, trigger: 'blur' }],
  haveMeal: [{ validator: validateHaveMeal, trigger: 'change' }],
  roomNum: [{ validator: validateRoomNum, trigger: 'blur' }],
  roots: [{ validator: validateRoots, trigger: 'change' }],
});
const rules = reactive<FormRules<typeof formData>>({
  roomType: [{ validator: validateRoomType, trigger: 'blur' }],
  peopleNum: [{ validator: validatePeopleNum, trigger: 'blur' }],
  price: [{ validator: validatePrice, trigger: 'blur' }],
  haveMeal: [{ validator: validateHaveMeal, trigger: 'change' }],
  roomNum: [{ validator: validateRoomNum, trigger: 'blur' }],
  roots: [{ validator: validateRoots, trigger: 'change' }],
});


const handleChange: UploadProps['onChange'] = async (file, fl) => {
  fileList.value=fl
};
const handleChange2: UploadProps['onChange'] = async (file, fl) => {
  fileList2.value=fl
};
//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  formEl.validate(async (valid) => {
    let fd=new FormData()
    Object.keys(formData.value).forEach(key=>{
      fd.append(key,formData.value[key])
    })
    
    if (fileList.value.length == 0) {
      alert('请现在要上传的文件')
      return
    }
     fileList.value.forEach(f=>{
      if (f.raw){
        fd.append('photo',f.raw)
      }
    })
    const ret=await $add(fd)
    if(ret.code === 2001){
      ElNotification({
          title: '成功',
          message: '新增成功！',
          type: 'success',
        })
        emit('sync-list')
    }else{
      ElNotification({
          title: '失败',
          message: '请联系管理员',
          type: 'error',
        })
    } 
    

  })
}

const submitForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  formEl.validate(async (valid) => {
    let fd=new FormData()
     Object.keys(formData2.value).forEach(key=>{
      if (key != 'facilityInfos' && key != 'roomtypeFacilities') {
        fd.append(key,formData2.value[key])        
      }
    })
    
    if (fileList2.value.length == 0) {
      alert('请现在要上传的文件')
      return
    }
    fileList2.value.forEach(f=>{
      if (f.raw){
        fd.append('photo',f.raw)
      }
    })
    const ret=await $update(fd)
    if(ret.code === 2001){
      ElNotification({
          title: '成功',
          message: '修改成功！',
          type: 'success',
        })
        emit('sync-list')
    }else{
      ElNotification({
          title: '失败',
          message: '请联系管理员',
          type: 'error',
        })
    } 

  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
   //清空表单
    formData.value = {
      roomType:'',
      peopleNum:'',
      price:'',
      haveMeal:'',
      roomNum:'',
      roots:[]
    }
}

const resetForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
   //清空表单
    formData2.value = {
      roomType:'',
      peopleNum:'',
      price:'',
      haveMeal:'',
      roomNum:'',
      roots:[],
    }
}

const facilityList = ref([])
const loadFacilityList = async()=>{
   facilityList.value = await $findFacility();
  //  roleList.value = data.t; // 确保 data 结构正确
    // roles.value = data.t
}

onMounted(()=>{
  loadFacilityList()
})

//暴露成员
defineExpose({
    drawer,
    drawer2,
    formData2
})

</script>

<style lang="scss" scoped>

</style>
